package com.lalameow.serverlogin.network;

import com.lalameow.packet.BasePack;
import com.lalameow.packet.enumtype.PackType;
import com.lalameow.packet.packImpl.EditPswPack;
import com.lalameow.packet.packImpl.LoginPack;
import com.lalameow.packet.packImpl.RegistPack;
import com.lalameow.serverlogin.api.NetClient;
import com.lalameow.serverlogin.client.config.ConfigManager;
import com.lalameow.serverlogin.network.handler.ClientHandler;
import com.lalameow.serverlogin.util.ModUitls;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;

/**
 * Created with IntelliJ IDEA.
 * 创建人: 陈刚
 * 日期: 2018/5/7
 * 时间: 20:29
 * 功能：请进行修改
 */
@SideOnly(Side.CLIENT)
public class McLoginClient implements NetClient {
    public static  ClientState clientState=ClientState.INITIAL;
    private SocketChannel socketChannel;

    @Override
    public void initClient()  {
        EventLoopGroup eventLoopGroup=new NioEventLoopGroup();
        Bootstrap bootstrap=new Bootstrap();
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE,true);
        bootstrap.group(eventLoopGroup);
       // bootstrap.remoteAddress("127.0.0.1", 7890);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(new IdleStateHandler(20,10,0));
                socketChannel.pipeline().addLast(new ObjectEncoder());
                socketChannel.pipeline().addLast(new ObjectDecoder(ClassResolvers.cacheDisabled(null)));
                socketChannel.pipeline().addLast(new ClientHandler());
            }
        });
        try {
            ChannelFuture future = bootstrap.connect(ConfigManager.loginGateHost, ConfigManager.loginGatePort).sync();
            if (future.isSuccess()) {
                socketChannel = (SocketChannel) future.channel();
                System.out.println("connect server  成功---------");
                McLoginClient.clientState=ClientState.START;
            }
        }catch (Exception e) {
            System.out.println("连接断开了！！！");
            McLoginClient.clientState=ClientState.EXCEPTION;
            socketChannel=null;

        }
    }

    @Override
    public void connectionServer() {


    }

    @Override
    public void getPublicKey() {

    }

    @Override
    public void login(String username,String password) {
        this.tryReconnection();
        if(socketChannel!=null){
            LoginPack loginPack=new LoginPack();
            loginPack.setUserName(username);
            loginPack.setPassword(password);
            loginPack.setMdsInfos(ModUitls.getMdsArray());
            BasePack b=new BasePack();
            b.setPackType(PackType.LOGIN);
            b.setBodyContent(PackType.LOGIN.getJsonContent(loginPack));
            socketChannel.writeAndFlush(b);
        }

    }

    @Override
    public void regist(RegistPack registPack) {
        this.tryReconnection();
        if(socketChannel!=null){
            BasePack b=new BasePack();
            b.setPackType(PackType.REGIST);
            b.setBodyContent(PackType.REGIST.getJsonContent(registPack));
            socketChannel.writeAndFlush(b);
        }
    }

    @Override
    public void forgetPwd() {

    }

    @Override
    public void updatePwd(String username,String oldPwd,String newPwd) {
        this.tryReconnection();
        if(socketChannel!=null){
            BasePack b=new BasePack();
            b.setPackType(PackType.EDITPSW);
            EditPswPack editPswPack=new EditPswPack();
            editPswPack.setUsername(username);
            editPswPack.setOldPwd(oldPwd);
            editPswPack.setNewPwd(newPwd);
            b.setBodyContent(PackType.EDITPSW.getJsonContent(editPswPack));
            socketChannel.writeAndFlush(b);
        }
    }

    /**
     * 尝试重连，如果连接异常的话
     */
    private void tryReconnection(){
        if(McLoginClient.clientState==ClientState.EXCEPTION){
            this.initClient();
        }
    }
}
